package org.quipu.client;

import java.util.List;
import org.quipu.client.events.AppEventBus;
import org.quipu.client.events.CategoriesOutOfDateEvent;
import org.quipu.dto.CategoryDto;

public class CategoryListBox extends AppListBox {

    private final CategoryDto.Type type;

    public CategoryListBox(AppEventBus eventBus, AppCache cache, CategoryDto.Type type, Long selectedCategoryId) {
        super(eventBus, cache, CategoriesOutOfDateEvent.class, null, selectedCategoryId);
        this.type = type;
        getListBox().addStyleName("categoriesList");
        refresh();
    }

    @Override
    protected final void refresh() {
        getListBox().clear();
        getListBox().addItem("", "0");
        int selectedIndex = -1;
        populateListBox(getCache().getCategoryTreeCache(type), 0);
        if(getSelectedId() != null) {
            for(int i = 0; i < getListBox().getItemCount(); i++) {
                if(getListBox().getValue(i).equals(String.valueOf(getSelectedId()))) {
                    selectedIndex = i;
                    break;
                }
            }
        }
        if(selectedIndex < 0) {
            setSelectedId(null);
        } else {
            getListBox().setSelectedIndex(selectedIndex);
        }
    }

    private void populateListBox(List<CategoryDto> categories, int depth) {
        if(!categories.isEmpty()) {
            String prefix = "";
            for(int d = 0; d < depth; d++) {
                prefix += "..";
            }
            for(CategoryDto category: categories) {
                getListBox().addItem(prefix + category.getTitle(), String.valueOf(category.getId()));
                populateListBox(category.getChilds(), depth + 1);
            }
        }
    }
}
